package com.taotao.tools.codec.sha;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * <p>
 *
 * </p>
 *
 * @author youbeiwuhuan
 * @version 1.0.0
 * @date 2023/11/14 11:52
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FileUtils {
    /**
     * 把一个文件转化为byte字节数组。
     *
     * @return
     */
    public static byte[] readFile(File file) {
        byte[] data;
        try (InputStream inputStream = Files.newInputStream(file.toPath());
             BufferedInputStream bis = new BufferedInputStream(inputStream);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            int len;
            byte[] buffer = new byte[1024];
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }

            data = bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return data;
    }


    public static String calSHA512(File input) throws Exception {
        return SHA512Utils.encrypt(readFile(input));
    }


    public static byte[] file2ByteArray(File file) throws IOException {

        FileInputStream stream = null;
        ByteArrayOutputStream out = null;
        try {
            stream = new FileInputStream(file);
            out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            // 此方法大文件OutOfMemory
            return out.toByteArray();
        } finally {
            try {
                stream.close();
                out.close();
            } catch (IOException e) {
            }

        }
    }


    public static File byteToFile(String filePath, byte[] data) throws IOException {
        File file = new File(filePath);
        BufferedOutputStream stream = null;
        FileOutputStream fstream = null;
        //byte[] data = new byte[(int) file.length()];
        try {
            fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(data);
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
                if (null != fstream) {
                    fstream.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return file;
    }


}
